package com.qf.service.impl;

import com.qf.dao.OrderDao;
import com.qf.dao.impl.OrderDaoimpl;
import com.qf.domain.Cartltem;
import com.qf.domain.Order;
import com.qf.domain.OrderDetail;
import com.qf.service.CartService;
import com.qf.service.OrderDetailService;
import com.qf.service.OrderService;
import com.qf.utils.DataSourceUtils;

import java.sql.SQLException;
import java.util.List;

public class OrderServiceimpl implements OrderService {
    private OrderDao orderDao=new OrderDaoimpl();
    @Override
    public void addOrder(Order order) {
        try {
            DataSourceUtils.getAutoCommit();
            //添加订单表
            orderDao.addOrder(order);
            OrderDetailService orderDetailService=new OrderDetailServiceimpl();
            //添加订单详情表
            //每一个商品都需要添加一个订单详情
            //pid 用户所对应的商品id  那么只能先查购物车，然后购物车里面有对应的商品id 然后遍历给他们
            CartService cartService=new CartServiceimpl();
            List<Cartltem> cartltems = cartService.selectUserCartAll(order.getUid());
            for (Cartltem cartltem:cartltems){
                OrderDetail orderDetail=new OrderDetail(0,order.getId(),cartltem.getPid(),cartltem.getNum(),cartltem.getMoney());
                orderDetailService.addOrderDetail(orderDetail);
                //删除购物车 用户id和商品id 都符合的商品  这样能精确删除
                cartService.deleteUserCart(order.getUid(),cartltem.getPid());
            }
            DataSourceUtils.Commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                DataSourceUtils.Rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }finally {
            try {
                DataSourceUtils.Closeone();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    @Override
    public void UpdateOrderstatus(String id, String s) {
        orderDao.UpdateOrderstatus(id,s);
    }

    @Override
    public List<Order> selectUserOne(Integer id) {

        return orderDao.selectUserOne(id);
    }

    @Override
    public Order selectIdOne(String oid) {

        return orderDao.selectIdOne(oid);
    }
}
